/* eslint-disable no-console */

import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'
import { useStateStore } from '@/store'

const store = useStateStore()

//加法
export const accAdd = (arg1, arg2) => {
  var r1, r2, m, c;
  try {
    r1 = arg1.toString().split(".")[1].length;
  }
  catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  }
  catch (e) {
    r2 = 0;
  }
  c = Math.abs(r1 - r2);
  m = Math.pow(10, Math.max(r1, r2));
  if (c > 0) {
    var cm = Math.pow(10, c);
    if (r1 > r2) {
      arg1 = Number(arg1.toString().replace(".", ""));
      arg2 = Number(arg2.toString().replace(".", "")) * cm;
    } else {
      arg1 = Number(arg1.toString().replace(".", "")) * cm;
      arg2 = Number(arg2.toString().replace(".", ""));
    }
  } else {
    arg1 = Number(arg1.toString().replace(".", ""));
    arg2 = Number(arg2.toString().replace(".", ""));
  }
  return (arg1 + arg2) / m;
}

//减法

export const accSub = (arg1, arg2) => {
  var r1, r2, m, n;
  try {
    r1 = arg1.toString().split(".")[1].length;
  }
  catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  }
  catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2));
  n = (r1 >= r2) ? r1 : r2;
  return ((arg1 * m - arg2 * m) / m).toFixed(n);
}

//乘法
export const accMul = (arg1, arg2) => {
  var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
  try {
    m += s1.split(".")[1].length;
  }
  catch (e) {
  }
  try {
    m += s2.split(".")[1].length;
  }
  catch (e) {
  }
  return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

//除法
export const accDiv = (arg1, arg2) => {
  var t1 = 0, t2 = 0, r1, r2;
  try {
    t1 = arg1.toString().split(".")[1].length;
  }
  catch (e) {
  }
  try {
    t2 = arg2.toString().split(".")[1].length;
  }
  catch (e) {
  }
  r1 = Number(arg1.toString().replace(".", ""));
  r2 = Number(arg2.toString().replace(".", ""));
  return (r1 / r2) * Math.pow(10, t2 - t1);
}

//金额加千分符
export const numFormat = (num) => {
  let res
  if (!num && num != 0 && num != '0') return false
  res = num.toString().replace(/\d+/, function (n) {
    return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
      return $1 + ","
    })
  })
  return res
}

// 检查是否有该菜单权限
export const isContains = (menuId) => {
  const menuIds = store.getMenuIds
  return menuIds.includes(menuId)
}

/**
 * http错误处理
 */
export const errorDeal = (error, url) => {
  // 特殊处理登录
  if (url == '/api/v1/auth/Token') {
    let message = ''
    if (error.result == 404) {
      message = '当前账号不存在！'
    }
    if (error.result == 331) {
      message = `密码错误，还可以输入${error.message}次！`
    }
    if (error.result == 407) {
      message = `当前账号已冻结，请2小时后再试！`
    }
    ElNotification({
      title: '提示',
      message: message,
      type: 'warning',
    })
    return
  }

  let errorText = error
  if (errorText.toString().indexOf('timeout') > -1) {
    errorText = '请求超时'
  } else if (error.response) {
    errorText = error.response.statusText
  } else if (error.request) {
    errorText = error.request
  } else if (error.message) {
    errorText = error.message
  } else if (error.msg) {
    errorText = error.msg
  }

  if (error.apiName) {
    errorText = `${error.apiName || ''},${errorText}`
  }

  if (error.code == '670' || error.code == 671) {
    ElMessageBox.alert(error.msg, '登录异常', {
      confirmButtonText: '确定',
      callback: (action) => {
        removeStore('USER_INFO_INRE')
        window.location.href = '#/'
        // window.location.reload()
      },
    })
  } else if (error.code == '722') {
    ElMessageBox.alert('当前用户非管理员,请重新登录', '提示', {
      confirmButtonText: '确定',
      callback: (action) => {
        removeStore('USER_INFO_INRE')
        window.location.href = '#/'
        // window.location.reload()
      },
    })
  } else if (error.code == '810') {
    ElMessageBox.alert('该接口仅限实名用户使用，请实名认证后再试', '提示', {
      confirmButtonText: '确定',
      callback: (action) => {
        // removeStore('USER_INFO_INRE')
        // window.location.href = '#/'
        // window.location.reload()
      },
    })
  } else if (error.code == '880') {
    ElMessageBox.alert('当前登录密码为初始密码，请修改密码', '提示', {
      confirmButtonText: '确定',
      callback: (action) => {
        // removeStore('USER_INFO_INRE')
        window.location.href = '#/editPass'
        // window.location.reload()
      },
    })
  } else {
    ElNotification({
      title: '提示',
      message: errorText,
      type: 'warning',
    })
  }
}
export const successDeal = (errorText) => {
  ElNotification({
    title: '提示',
    message: errorText,
    type: 'success',
  })
}

export const warningDeal = (errorText) => {
  ElNotification({
    title: '提示',
    message: errorText,
    type: 'warning',
  })
}

export const successMsg = (text) => {
  ElMessage({
    message: text,
    type: 'success',
  })
}

/**
 * @describe 获取窗口宽高
 * @param
 * @return {Object}
 **/
export const getWindowWidthAndHeight = () => {
  return {
    windowHeight:
      document.documentElement.clientHeight ||
      window.innerHeight ||
      document.body.clientHeight,
    windowWidth:
      document.documentElement.clientWidth ||
      window.innerWidth ||
      document.body.clientWidth,
  }
}
/**
 * 全局loading
 */
export const globalLoading = (off) => {
  if (off) {
    !window.GlobalLoadingTimer && (window.GlobalLoadingTimer = [])
    window.GlobalLoadingTimer.push(
      setTimeout(() => {
        globalLoadingClear()
        store.setLoadingGlobal(true)
      }, 100)
    )
  } else {
    globalLoadingClear()
    store.setLoadingGlobal(false)
  }
}
// 清除
const globalLoadingClear = () => {
  if (window.GlobalLoadingTimer) {
    window.GlobalLoadingTimer.forEach((item) => {
      clearTimeout(item)
    })
  }
}
/**
 * 存储localStorage
 */
export const setStore = (name, content) => {
  if (!name) return
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  window.localStorage.setItem(name, content)
}

/**
 * 获取localStorage
 */
export const getStore = (name) => {
  if (!name) return
  let content = window.localStorage.getItem(name)
  return content ? JSON.parse(content) : ''
}

/**
 * 删除localStorage
 */
export const removeStore = (name) => {
  if (!name) return
  window.localStorage.removeItem(name)
}
/**
 * 时间戳格式化
 */
export const getDateTime = function (timestamp) {
  let t = null
  if (!timestamp) {
    return '--'
  }
  // 不传值，则获取当前时间
  if (timestamp === undefined) {
    t = new Date()
  } else if (timestamp) {
    t = new Date(parseInt(timestamp))
  }

  if (t) {
    var n = t.getFullYear()
    var a = t.getMonth() + 1
    var r = t.getDate()
    var o = t.getHours()
    var i = t.getMinutes()
    var s = t.getSeconds()

    a >= 10 || (a = '0' + a),
      r >= 10 || (r = '0' + r),
      o >= 10 || (o = '0' + o),
      i >= 10 || (i = '0' + i),
      s >= 10 || (s = '0' + s)

    return [
      n, // yy
      a, // mm
      r, // dd
      n + '-' + a, // yy-mm
      a + '/' + r, // mm/dd
      o + ':' + i + ':' + s, // hh:mm:ss
      n + '-' + a + '-' + r + ' ' + o + ':' + i + ':' + s, // yy-mm-dd hh:mm::ss
      a + '-' + r + ' ' + o + ':' + i + ':' + s, // mm-dd hh:mm::ss
      n + '-' + a + '-' + r, // yy-mm-dd
      n + a + r, // yymmdd
      n + a, //yymm
      n + '-' + a + '-' + r + ' ' + o + ':' + i, // yy-mm-dd hh:mm
    ]
  } else {
    return ['--', '--', '--', '--', '--', '--', '--', '--', '--', '--']
  }
}

/**
 *  获取7天前的时间
 */

export const getSevenTime = () => {
  let now = new Date()
  let sevendate = new Date(now.getTime() - 7 * 24 * 3600 * 1000)
  let sevenyear = sevendate.getFullYear()
  let sevenmonth = sevendate.getMonth() + 1
  let sevenday = sevendate.getDate()
  let sevenhour = sevendate.getHours()
  let sevenminute = sevendate.getMinutes()
  let sevensecond = sevendate.getSeconds()
  sevenmonth >= 10 || (sevenmonth = '0' + sevenmonth),
    sevenday >= 10 || (sevenday = '0' + sevenday),
    sevenhour >= 10 || (sevenhour = '0' + sevenhour),
    sevenminute >= 10 || (sevenminute = '0' + sevenminute),
    sevensecond >= 10 || (sevensecond = '0' + sevensecond)
  let sevenTime = `${sevenyear}-${sevenmonth}-${sevenday} ${sevenhour}:${sevenminute}:${sevensecond}`

  return sevenTime
}

/**
 * 获取各种类型当前时间
 */
export const getPresentTime = () => {
  let date = new Date() //获取当前时间国标版
  let year = date.getFullYear() // 获取年
  let month = date.getMonth() + 1 //获取当前月
  let day = date.getDate() //日
  let hour = date.getHours() //时
  let minute = date.getMinutes() //分
  let second = date.getSeconds() //秒

  month >= 10 || (month = '0' + month),
    day >= 10 || (day = '0' + day),
    hour >= 10 || (hour = '0' + hour),
    minute >= 10 || (minute = '0' + minute),
    second >= 10 || (second = '0' + second)
  let nowTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`
  return nowTime
}

/**
 * 日期转时间戳
 */
export const getUnixTime = (e) => {
  var t
  if (e) {
    if (typeof e === 'string') e = e.replace(/-/g, '/').replace(/T|Z/g, ' ')
    t = new Date(e)
  } else t = new Date()
  return t.getTime()
}

/**
 * 日期转时间戳
 */
export const getTimestamp = (e) => {
  var t
  if (e) {
    e = e.replace(/-/g, '/')
    t = new Date(e)
  } else t = new Date()
  return t.getTime().toString()
}
/**
 * 日期加上‘-’
 */
export const getJoinDate = (e) => {
  e = e.toString()
  let year = e.substring(0, 4)
  let month = e.substring(4, 6)
  let day = e.substring(6, 8)
  let date = `${year}-${month}-${day}`
  return date
}
/**
 * 数组去重
 */
export const unique = (arr) => {
  return Array.from(new Set(arr))
}
/**
 * 获取地址栏参数
 */
export const getUrlParam = (e, url) => {
  var t = new RegExp('(^|&)' + e + '=([^&]*)(&|$)')

  var n = url ? url.match(t) : window.location.search.substr(1).match(t)
  return n != null ? unescape(n[2]) : ''
}
/**
 * 哈希路由获取地址栏参数
 */

export const getUrlKey = (name) => {
  return (
    decodeURIComponent(
      (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
        location.href
      ) || [, ''])[1].replace(/\+/g, '%20')
    ) || null
  )
}

/**
 * 秒数格式化
 */
export const secondsFormat = (v = 0) => {
  v = parseInt(v)
  var day, minute, second, hour
  day = Math.floor(v / (60 * 60 * 24))
  hour = Math.floor((v % (60 * 60 * 24)) / (60 * 60))
  minute = Math.floor((v % (60 * 60)) / 60)
  second = Math.floor(v % 60)
  hour < 10 && (hour = '0' + hour)
  minute < 10 && (minute = '0' + minute)
  second < 10 && (second = '0' + second)
  return day != '00'
    ? day + '天' + hour + ':' + minute + ':' + second
    : hour != '00'
      ? hour + ':' + minute + ':' + second
      : minute != '00'
        ? minute + ':' + second
        : '00:' + second
}
/**
 * 手机格式化
 */
export const phoneFormat = (value, isNum) => {
  if (!value) return '--'
  if (isNum) {
    value = parseInt(value).toString()
  } else value = value.toString()

  let len = value.length
  let w = value.split('')
  w.splice(3, 0, ' ')
  w.splice(8, 0, ' ')
  w = w.join('')
  return w
}

/**
 * 去抖动函数
 */
export const debounce = function (func, wait) {
  var timeout
  return function () {
    var context = this
    var args = arguments
    clearTimeout(timeout)
    timeout = setTimeout(function () {
      func.apply(context, args)
    }, wait)
  }
}
/**
 * iframe 文件下载
 */
export const createDownload = (url, data, cb) => {
  var body = document.getElementsByTagName('body')[0]
  var ifr = document.getElementById('downLoadForm')
  var form = document.createElement('form')
  var input = document.createElement('input')
  if (!ifr) {
    ifr = document.createElement('iframe')
    ifr.setAttribute('id', 'downLoadForm')
    ifr.setAttribute('name', 'downLoadForm')
    ifr.setAttribute('style', 'display:none')
  }
  cb()
  ifr.addEventListener('load', function (e) {
    try {
      var res = ifr.contentWindow.document.body.textContent
      if (res != '' && res.indexOf('code') > -1) {
        var result = JSON.parse(res)
        if (res.code != 200) {
          errorDeal(result)
        }
      }
    } catch (error) {
      errorDeal(error)
    }
  })

  form.setAttribute('style', 'display:none')
  form.setAttribute('target', 'downLoadForm')
  form.setAttribute(
    'enctype',
    'application/x-www-form-urlencoded;charset=utf-8'
  )
  form.setAttribute('method', 'post')
  form.setAttribute('action', url)

  input.setAttribute('type', 'hidden')
  input.setAttribute('name', 'data')
  input.setAttribute('value', data)

  body.appendChild(ifr)
  body.appendChild(form)

  form.appendChild(input)
  form.submit()
  form.remove()
}

/* 文件流下载 */
export const BlobDownLoad = (res, name) => {
  let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
  const link = document.createElement('a')
  link.href = window.URL.createObjectURL(blob)
  link.download = name
  link.click()
  document.body.appendChild(link)
}
/* 文件地址下载 */
export const locationDownLoad = (url) => {
  if (!url) {
    errorDeal('无下载地址')
    return false
  }
  const link = document.createElement('a')
  link.href = url
  link.click()
  document.body.appendChild(link)
}
/**
 * 正则验证函数
 */
export const regularValid = function (type, value) {
  let valid = false

  switch (type) {
    case 'float': // 保留后两位校验
      valid = /^[-+]?[0-9]+\.?[0-9]{0,2}$/.test(value)
      break
    case 'int+': // 正整数
      valid = /^[1-9]+$/.test(value)
      break
    case 'phone': // 手机号码校验
      valid = /^1[3-9]\d{9}$/.test(value)
      break
    case 'name': // 账户名，数字+字母+下划线组合
      valid = !/\W+/.test(value)
      break
    case 'password': // 密码校验，非法字符
      valid =
        !/[`~()|{}':;',\[\].<>/?~！￥……&*（）——|{}【】‘；：”“'。，、？]/.test(
          value
        )
      break
    case 'email': // 邮箱
      valid = /^\w+@[a-z0-9]+\.[a-z]+$/.test(value)
      break
  }
  return valid
}

/**
 * 正则验证函数
 */
export const passwordValid = function (str) {
  let obj = {
    valid: true,
    text: '',
  }

  let zmReg = /[A-Za-z]/ // 大小写字母
  let numReg = /[0-9]/ // 数字
  let zfReg = /[^A-Za-z0-9\s]/ // 特殊字符不包含空格
  let kgReg = /^[^\s]*$/ // 不能有空格
  let zwReg = new RegExp('[\u4E00-\u9FA5]+') // 不能有中文
  let complex = 0

  if (str == undefined || !str.length) {
    obj.valid = false
    obj.text = '密码不能为空！'
    return obj
  }

  if (!kgReg.test(str)) {
    obj.valid = false
    obj.text = '密码不能有空格！'
    return obj
  }

  if (zwReg.test(str)) {
    obj.valid = false
    obj.text = '密码不能有中文！'
    return obj
  }

  if (str.length < 6) {
    obj.valid = false
    obj.text = '密码不能少于6位字符！'
    return obj
  }

  if (str.length > 20) {
    obj.valid = false
    obj.text = '密码不能多于20位字符！'
    return obj
  }

  if (zmReg.test(str)) {
    ++complex
  }

  if (numReg.test(str)) {
    ++complex
  }

  if (zfReg.test(str)) {
    ++complex
  }

  // if (complex < 2) {
  //   // 密码需包含字母，符号或者数字中至少两项且长度超过8位数，最多不超过16位数
  //   obj.valid = false
  //   obj.text = '密码必须包含字母、数字、符号中至少2种！'
  //   return obj;
  // }

  return obj
}

/**
 * 数字格式化
 */
export const numberFormat = function (num, pro = 100) {
  return num
    ? parseFloat((parseFloat(num) / pro).toFixed(2))
      .toString()
      .replace(/\d+/, function (n) {
        return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
          return $1 + ','
        })
      })
    : 0.0
}
export const getNumberDateTime = function (value) {
  if (value) {
    var secondTime = parseInt(value) // 秒
    var minuteTime = 0 // 分
    var hourTime = 0 // 小时
    if (secondTime > 60) {
      //如果秒数大于60，将秒数转换成整数
      //获取分钟，除以60取整数，得到整数分钟
      minuteTime = parseInt(secondTime / 60)
      //获取秒数，秒数取佘，得到整数秒数
      secondTime = parseInt(secondTime % 60)
      //如果分钟大于60，将分钟转换成小时
      if (minuteTime > 60 || minuteTime == 60) {
        //获取小时，获取分钟除以60，得到整数小时
        hourTime = parseInt(minuteTime / 60)
        //获取小时后取佘的分，获取分钟除以60取佘的分
        minuteTime = parseInt(minuteTime % 60)
      }
    }
    var result = ''
    if (secondTime > 0) {
      result = '' + parseInt(secondTime) + '秒'
    }
    if (minuteTime > 0) {
      result = '' + parseInt(minuteTime) + '分' + result
    }
    if (hourTime > 0) {
      result = '' + parseInt(hourTime) + '小时' + result
    }
    return result
  } else {
    return '--'
  }
}

export const bytesToSize = function (bytes, type) {
  if (bytes === 0) return '0 B'
  var k = 1024 // or 1024
  var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  if (type) {
    sizes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  } else {
    sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  }
  var i = Math.floor(Math.log(bytes) / Math.log(k))

  return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]
}

export const bytesToSize2 = function (limit) {
  var size = ''
  if (limit < 1024) {
    //小于0.1KB，则转化成B
    size = limit.toFixed(2) + 'B'
  } else if (limit < 1024 * 1024) {
    //小于0.1MB，则转化成KB
    size = (limit / 1024).toFixed(2) + 'KB'
  } else if (limit < 1024 * 1024 * 1024) {
    //小于0.1GB，则转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
  } else {
    //其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
  }

  var sizeStr = size + '' //转成字符串
  var index = sizeStr.indexOf('.') //获取小数点处的索引
  var dou = sizeStr.substr(index + 1, 2) //获取小数点后两位的值
  if (dou == '00') {
    //判断后两位是否为00，如果是则删除00
    return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
  }
  return size
}

//初始化时间戳(毫秒)
export const initDatepicker = function (name, time = '') {
  if (!name) return
  let b = ''
  switch (name) {
    case 1: // 当前时间戳
      b = new Date().getTime()
      break
    case 2: // 当天的(00时00分00秒)
      b = new Date(new Date().toLocaleDateString()).getTime()
      break
    case 3: // 当天的(23时23分59秒)
      b =
        new Date(new Date().toLocaleDateString()).getTime() -
        999 +
        24 * 60 * 60 * 1000
      break

    case 4: // 自定义时间 (当天的00时00分00秒 - 时间戳)
      b = new Date(new Date().toLocaleDateString()).getTime() - time
      break
  }
  return b
}

export const getExplorerInfo = function () {
  var explorer = window.navigator.userAgent.toLowerCase()
  //ie
  if (explorer.indexOf('msie') >= 0) {
    var ver = explorer.match(/msie ([\d.]+)/)[1]
    return `IE${ver}`
  }
  //firefox
  else if (explorer.indexOf('firefox') >= 0) {
    var ver = explorer.match(/firefox\/([\d.]+)/)[1]
    return `Firefox${ver}`
  }
  //Chrome
  else if (explorer.indexOf('chrome') >= 0) {
    var ver = explorer.match(/chrome\/([\d.]+)/)[1]
    return `Chrome${ver}`
  }
  //Opera
  else if (explorer.indexOf('opera') >= 0) {
    var ver = explorer.match(/opera.([\d.]+)/)[1]
    return `Opera${ver}`
  }
  //Safari
  else if (explorer.indexOf('Safari') >= 0) {
    var ver = explorer.match(/version\/([\d.]+)/)[1]
    return `Safari${ver}`
  }
}

// 加千分号
export const toThousands = function (num) {
  if (!num) {
    return 0
  }
  let result =
    num.toString().indexOf('.') !== -1
      ? num.toLocaleString()
      : num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
  return result
}

// 秒转 分时天
export const formatSecToStr = function (seconds) {
  let daySec = 24 * 60 * 60
  let hourSec = 60 * 60
  let minuteSec = 60
  let dd = Math.floor(seconds / daySec)
  let hh = Math.floor((seconds % daySec) / hourSec)
  let mm = Math.floor((seconds % hourSec) / minuteSec)
  let ss = seconds % minuteSec
  if (dd > 0) {
    return dd + '天' + hh + '小时' + mm + '分钟'
  } else if (hh > 0) {
    return hh + '小时' + mm + '分钟'
  } else if (mm > 0) {
    return mm + '分钟'
  } else {
    return ss + '秒'
  }
}
/**
 * 标准时间转年月日
 */
export const timestampToTime = (timestamp) => {
  let date = new Date(timestamp)
  let y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? '0' + m : m
  let d = date.getDate()
  d = d < 10 ? '0' + d : d
  let h = date.getHours()
  let minute = date.getMinutes()
  minute = minute < 10 ? '0' + minute : minute
  let second = date.getSeconds()
  second = second < 10 ? '0' + second : second
  return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
}

//  base64转换成file对像
export const base64ToFile = function (data) {
  // 将base64 的图片转换成file对象上传 atob将ascii码解析成binary数据
  let binary = atob(data.split(',')[1])
  let mime = data.split(',')[0].match(/:(.*?);/)[1]
  let array = []
  for (let i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i))
  }
  let fileData = new Blob([new Uint8Array(array)], {
    type: mime,
  })

  let file = new File([fileData], `${new Date().getTime()}.png`, {
    type: mime,
  })

  return file
}

// 百度经纬度转高德
export const baiduToGaode = function (bd_lat, bd_lon) {
  let x_pi = (3.14159265358979324 * 3000.0) / 180.0
  let x = Number(bd_lon - 0.0065)
  let y = Number(bd_lat - 0.006)
  let z = Number(Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi))
  let theta = Number(Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi))
  bd_lon = Number(z * Math.cos(theta))
  bd_lat = Number(z * Math.sin(theta))
  let list = [bd_lon, bd_lat]
  return list
}

//是否是闰年
export const isLeapYear = function (year) {
  if (year / 4 == 0 && year / 100 != 0) {
    return true
  } else if (year / 400 == 0) {
    return true
  } else {
    return false
  }
}
//根据年月得到天数
export const getDayNumByYearMonth = function (year, month) {
  switch (month) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
      return 31
      break
    case 4:
    case 6:
    case 9:
    case 11:
      return 30
      break
    case 2:
      return isLeapYear(year) ? 29 : 28
  }
}
/**
 * 传月份获取月份第一天和最后一天的时间戳
 */
export const getMonthStamp = function (timeStamp) {
  let inDate = new Date(timeStamp)
  let year = inDate.getFullYear()
  let month = inDate.getMonth()
  let startTime = new Date(year, month, 1).getTime()
  let endTime = ''
  endTime = new Date(year, month + 1, 1).getTime() - 1
  return {
    startTime: startTime,
    endTime: endTime,
  }
}

/**
 * 获取地图坐标最西南角
 */
export const getSW = (list, offset) => {
  let south = null
  let west = null
  for (let item of list) {
    if (item.lng != 0 && item.lat != 0) {
      if ((west && item.lng < west) || !west) {
        west = item.lng
      }
      if ((south && item.lat < south) || !south) {
        south = item.lat
      }
    }
  }
  return [west - offset, south - offset]
}

/**
 * 获取地图坐标最东北角
 */
export const getNE = (list, offset) => {
  let north = null
  let east = null
  for (let item of list) {
    if (item.lng != 0 && item.lat != 0) {
      if ((east && item.lng > east) || !east) {
        east = item.lng
      }
      if ((north && item.lat > north) || !north) {
        north = item.lat
      }
    }
  }

  return [east + offset, north + offset]
}


/**
 *计算两个日期之间的差值   接受的日期格式为“20201-1”，“20201/1”等
 */
export const getDiffDay = (date_1, date_2) => {
  //
  let totalDays, diffDate
  let myDate_1 = Date.parse(date_1)
  let myDate_2 = Date.parse(date_2)
  // 将两个日期都转换为毫秒格式，然后做差
  diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值

  totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
  // console.log(totalDays)

  return totalDays // 相差的天数
}
